package com.ruoyi.web.controller.community;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.community.domain.*;
import com.ruoyi.community.mapper.*;
import com.ruoyi.community.service.help.HelpCommentsService;
import com.ruoyi.community.service.help.HelpGoodsService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

//小程序端帮购商品页

@RestController
@RequestMapping("/community/helphelp")
public class HelpGoodsAppController extends BaseController {

    @Autowired
    HelpGoodsService helpGoodsService;

    @Autowired
    HelpGoodsMapper helpGoodsMapper;

    @Autowired
    HelpCommentMapper helpCommentMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    HelpVoteMapper helpVoteMapper;

    @Autowired
    HelpVoteOptionMapper helpVoteOptionMapper;

    @Autowired
    HelpVoteResultMapper helpVoteResultMapper;

    @Autowired
    HelpVoteComment1Mapper helpVoteComment1Mapper;

    @Autowired
    HelpVoteComment2Mapper helpVoteComment2Mapper;

    @Autowired
    HelpInfoMapper helpInfoMapper;

    @Autowired
    HelpVoteComment1LikeMapper helpVoteComment1LikeMapper;

    @Autowired
    HelpVoteComment2LikeMapper helpVoteComment2LikeMapper;


    /**
     * 帮购基本信息
     *
     */
    @GetMapping("/info")
    public AjaxResult info()
    {
        Integer i = SecurityUtils.getCommunityId();
        HelpInfo helpInfo = helpInfoMapper.selectByCommunityId(i);

        return  AjaxResult.success(helpInfo);

    }



    /**
     * 帮购在售商品列表
     * @param
     * @return
     */
    @GetMapping("/goodslist")
    public AjaxResult goodsList()
    {
        Integer i = SecurityUtils.getCommunityId();
        List<HelpGoods> helpGoodsList = helpGoodsService.selectHelpGoodsListByCommunityId(i);

        return  AjaxResult.success(helpGoodsList);

    }

    /**
     * 搜索帮购在售商品列表
     * @param
     * @return
     */
    @GetMapping("/goodsSearch")
    public AjaxResult goodsSearch(String name)
    {
        Integer i = SecurityUtils.getCommunityId();
        Map map =new HashMap();
        map.put("communityId",i);
        map.put("name",name);
        List<HelpGoods> helpGoodsList = helpGoodsMapper.selectByCommunityIdAndName(map);
        return  AjaxResult.success(helpGoodsList);

    }

    /**
     * 帮购在售商品精选列表
     * @param
     * @return
     */
    @GetMapping("/goodslistTop")
    public AjaxResult goodsListTop()
    {
        Integer i = SecurityUtils.getCommunityId();
        List<HelpGoods> helpGoodsList = helpGoodsService.selectHelpGoodsListByCommunityId(i);

        //这里根据评分排名
        List<HelpGoods> listSort = helpGoodsList.stream().sorted(Comparator.comparing(HelpGoods::getRating).reversed()).collect(Collectors.toList());
        if(listSort.size()<=5){
            return  AjaxResult.success(listSort);
        }
        //System.out.println(listSort);
        return  AjaxResult.success(listSort.subList(0,4));

    }



    /**
     * 帮购下架商品列表
     * @param
     * @return
     */
    @GetMapping("/xiajia")
    public AjaxResult goodsList1()
    {
        Integer i = SecurityUtils.getCommunityId();
        //System.out.println(i);
        List<HelpGoods> helpGoodsList = helpGoodsService.selectHelpGoodsListByCommunityId1(i);

        return  AjaxResult.success(helpGoodsList);

    }

    /**
     * 搜索帮购下架商品列表
     * @param
     * @return
     */
    @GetMapping("/xiajiaSearch")
    public AjaxResult goodsSearch1(String name)
    {
        Integer i = SecurityUtils.getCommunityId();
        Map map =new HashMap();
        map.put("communityId",i);
        map.put("name",name);
        List<HelpGoods> helpGoodsList = helpGoodsMapper.selectByCommunityIdAndName1(map);
        return  AjaxResult.success(helpGoodsList);

    }

    /**
     * 帮购下架商品列表精选
     * @param
     * @return
     */
    @GetMapping("/xiajiaTop")
    public AjaxResult goodsList1Top()
    {
        Integer i = SecurityUtils.getCommunityId();
        //System.out.println(i);
        List<HelpGoods> helpGoodsList = helpGoodsService.selectHelpGoodsListByCommunityId1(i);
        //这里根据总销量排名
        List<HelpGoods> listSort = helpGoodsList.stream().sorted(Comparator.comparing(HelpGoods::getTotalSales).reversed()).collect(Collectors.toList());
        if(listSort.size()<=5){
            return  AjaxResult.success(listSort);
        }
        //System.out.println(listSort);
        return  AjaxResult.success(listSort.subList(0,4));

    }

    /**
     * 帮购商品详情
     * @param
     * @return
     */
    @GetMapping("/detail")
    public AjaxResult goodDetail(Long id)
    {
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy/MM/dd");
        HelpGoods h = helpGoodsService.selectHelpGoodsByPrimaryKey(id);
        h.setEndTime1(sdf.format(h.getEndTime()));
        return  AjaxResult.success(h);

    }


    /**
     * 帮购商品评价列表
     * @param
     * @return
     */
    @GetMapping("/comments")
    public AjaxResult goodComment(Long id)
    {
        List<HelpComment> helpCommentList = helpCommentMapper.selectByGoodsId(id);
        for(int i=0;i<helpCommentList.size();i++)
        {
            HelpComment h = helpCommentList.get(i);
            Long userId = h.getUserId();
            SysUser u = userService.selectUserById(userId);
            h.setUserName(u.getUserName());
            h.setUserPicture(u.getAvatar());
        }
        return  AjaxResult.success(helpCommentList);

    }

    /**
     * 帮购查询投票信息
     */

    @GetMapping("/voteInfo")
    public AjaxResult voteInfo()
    {
        Integer i = SecurityUtils.getCommunityId();
        List<HelpVote> helpVotes = helpVoteMapper.selectHelpVotesByCommunityId(i);
        HelpVote h = helpVotes.get(helpVotes.size()-1);
        List<HelpVoteOption> options =new ArrayList<HelpVoteOption>();
        options = helpVoteOptionMapper.selectByVoteId(h.getVoteId());

        int q = 0;
        for(int j=0;j<options.size();j++){
            q+=options.get(j).getNum();
        }

        Long userId = SecurityUtils.getUserID();
        for(int j=0;j<options.size();j++){
            HelpVoteOption a = options.get(j);
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format((float)a.getNum()/(float)q*100)+"%";
            a.setSpeed(result);

//
//            List<HelpVoteResult> res = helpVoteResultMapper.selectByOption(a.getOptionId());
//            //查询用户是否已经投过票
//            for(int w=0;w<res.size();w++){
//                if(res.get(w).getUserId() == userId){
//                    a.setCollect(true);
//                    break;
//                }
//            }
            Map map = new HashMap();
            map.put("userId",userId);
            map.put("optionId",a.getOptionId());
            if(helpVoteResultMapper.selectByOptionAndUserId(map).size()>0){
                a.setCollect(true);
            };

        }

        h.setOptions(options);
        return  AjaxResult.success(h);

    }


    /**
     * 帮购投票
     */

    @PostMapping("/vote")
    public AjaxResult vote(@RequestBody HelpVoteOption helpVoteOption){
        //System.out.println(helpVoteOption+"   bxsncsmksamxsncuisncxkasx");
        HelpVoteOption o = helpVoteOptionMapper.selectByPrimaryKey(helpVoteOption.getOptionId());
        o.setNum(o.getNum()+1);
        HelpVoteResult r = new HelpVoteResult();
        r.setDate(new Date());
        r.setUserId(SecurityUtils.getUserID());
        r.setOptionId(helpVoteOption.getOptionId());
        r.setVoteId(o.getVoteId());
        helpVoteResultMapper.insertSelective(r);
        return AjaxResult.success(helpVoteOptionMapper.updateByPrimaryKey(o));

    }

    /**
     * 帮购取消投票
     */

    @PostMapping("/voteDelete")
    public AjaxResult voteDelete(@RequestBody HelpVoteOption helpVoteOption){
        Long userId = SecurityUtils.getUserID();
        //System.out.println(helpVoteOption+"   bxsncsmksamxsncuisncxkasx");
        HelpVoteOption o = helpVoteOptionMapper.selectByPrimaryKey(helpVoteOption.getOptionId());
        o.setNum(o.getNum()-1);
//        HelpVoteResult r = new HelpVoteResult();
//        r.setDate(new Date());
//        r.setUserId(SecurityUtils.getUserID());
//        r.setOptionId(helpVoteOption.getOptionId());
//        r.setVoteId(o.getVoteId());
//        helpVoteResultMapper.insertSelective(r);
        List<HelpVoteResult> res = helpVoteResultMapper.selectByOption(helpVoteOption.getOptionId());
        for(int w=0;w<res.size();w++){
            if(res.get(w).getUserId() == userId){
                helpVoteResultMapper.deleteByPrimaryKey(res.get(w).getResultId());
                break;
            }
        }
        return AjaxResult.success(helpVoteOptionMapper.updateByPrimaryKey(o));

    }

    /**
     * 帮购查询投票评论
     */
    @GetMapping("/voteComments")
    public AjaxResult voteComment(Integer voteId)
    {
        List<HelpVoteComment1> helpVoteComment1List = helpVoteComment1Mapper.selectCommentsByVoteId(voteId);
        for(int i=0;i<helpVoteComment1List.size();i++)
        {
            HelpVoteComment1 h = helpVoteComment1List.get(i);
            Long userId = h.getUserId();
            SysUser u = userService.selectUserById(userId);
            h.setUserName(u.getUserName());
            h.setUserPicture(u.getAvatar());
//            List<HelpVoteComment1Like> res = helpVoteComment1LikeMapper.selectByComment1Id(h.getCommentId());
//            for(int w=0;w<res.size();w++){
//                if(res.get(w).getUserId() == userId){
//                   h.setChange(true);
//                    break;
//                }
//            }

            Map map = new HashMap();
            map.put("comment1Id",h.getCommentId());
            map.put("userId",SecurityUtils.getUserID());
            if(helpVoteComment1LikeMapper.selectByComment1IdAndUserId(map).size()>0)
            {
                h.setChange(true);
            }

            h.setOpen(false);
            Integer commentId = h.getCommentId();
            List<HelpVoteComment2> helpVoteComment2List = helpVoteComment2Mapper.selectCommentsByComment1Id(commentId);
            for (int j = 0;j<helpVoteComment2List.size();j++){
                HelpVoteComment2 h2 = helpVoteComment2List.get(j);
                Long userId2 = h2.getUserId();
                SysUser u2 = userService.selectUserById(userId2);
                h2.setUserName(u2.getUserName());
                h2.setUserPicture(u2.getAvatar());
//                List<HelpVoteComment2Like> res1 = helpVoteComment2LikeMapper.selectByComment2Id(h2.getCommentId());
//                for(int w=0;w<res1.size();w++){
//                    if(res1.get(w).getUserId() == userId){
//                        h2.setChanges(true);
//                        break;
//                    }
//                }
                Map map1 = new HashMap();
                map1.put("comment2Id",h2.getCommentId());
                map1.put("userId",SecurityUtils.getUserID());
                if(helpVoteComment2LikeMapper.selectByComment2IdAndUserId(map1).size()>0)
                {
                    h2.setChanges(true);
                }
            }
            h.setReplyList(helpVoteComment2List);
        }
        return  AjaxResult.success(helpVoteComment1List);

    }


    /**
     * 帮购查询精选投票评论
     */
    @GetMapping("/jingxuanComments")
    public AjaxResult collectComment()
    {
        Integer q = SecurityUtils.getCommunityId();
        List<HelpVote> helpVotes = helpVoteMapper.selectHelpVotesByCommunityId(q);
        HelpVote s = helpVotes.get(helpVotes.size()-1);
        List<HelpVoteComment1> helpVoteComment1List = helpVoteComment1Mapper.selectCommentsByVoteId(s.getVoteId());
        List<HelpVoteComment1> listSort = helpVoteComment1List.stream().sorted(Comparator.comparing(HelpVoteComment1::getLike).reversed()).collect(Collectors.toList());
        //System.out.println(listSort);
        List<HelpVoteComment1> result =new ArrayList<>();
        if(listSort.size()<=3) {
            for (int i = 0; i < listSort.size(); i++) {
                HelpVoteComment1 h = listSort.get(i);
                Long userId = h.getUserId();
                SysUser u = userService.selectUserById(userId);
                h.setUserName(u.getUserName());
                h.setUserPicture(u.getAvatar());
                List<HelpVoteComment1Like> res = helpVoteComment1LikeMapper.selectByComment1Id(h.getCommentId());
                for(int w=0;w<res.size();w++){
                    if(res.get(w).getUserId() == userId){
                        h.setChange(true);
                        break;
                    }
                }
                h.setOpen(false);
                result.add(h);
            }
        }
        else{
            for (int i = 0; i < 3; i++) {
                HelpVoteComment1 h = listSort.get(i);
                Long userId = h.getUserId();
                SysUser u = userService.selectUserById(userId);
                h.setUserName(u.getUserName());
                h.setUserPicture(u.getAvatar());
                List<HelpVoteComment1Like> res = helpVoteComment1LikeMapper.selectByComment1Id(h.getCommentId());
                for(int w=0;w<res.size();w++){
                    if(res.get(w).getUserId() == userId){
                        h.setChange(true);
                        break;
                    }
                }
                h.setOpen(false);
                result.add(h);

            }

        }
        return  AjaxResult.success(result);

    }

    /**
     * 帮购一级评论
     */
    @PostMapping("/voteComment1")
    public AjaxResult voteComment1(@RequestBody HelpVoteComment1 helpVoteComment1){
        //System.out.println(helpVoteOption+"   bxsncsmksamxsncuisncxkasx");
        //Integer i = SecurityUtils.getCommunityId();
        //HelpVoteComment1 h = new HelpVoteComment1();
        //helpVoteComment1.setContent(content);
        //System.out.println(helpVoteComment1.getContent());
        //System.out.println(helpVoteComment1.getVoteId());
        helpVoteComment1.setLike(0);
        helpVoteComment1.setDate(new Date());
        helpVoteComment1.setUserId(SecurityUtils.getUserID());

        return AjaxResult.success(helpVoteComment1Mapper.insert(helpVoteComment1));

    }



    /**
     * 帮购二级评论
     */
    @PostMapping("/voteComment2")
    public AjaxResult voteComment2(@RequestBody HelpVoteComment2 helpVoteComment2){
        //System.out.println(helpVoteOption+"   bxsncsmksamxsncuisncxkasx");
        //Integer i = SecurityUtils.getCommunityId();
        //HelpVoteComment1 h = new HelpVoteComment1();
        //helpVoteComment1.setContent(content);
        //System.out.println(helpVoteComment1.getContent());
        //System.out.println(helpVoteComment1.getVoteId());
        helpVoteComment2.setLike(0);
        helpVoteComment2.setDate(new Date());
        helpVoteComment2.setUserId(SecurityUtils.getUserID());

        return AjaxResult.success(helpVoteComment2Mapper.insert(helpVoteComment2));

    }

    /**
     * 帮购一级评论点赞
     */
    @PostMapping("/voteComment1Like")
    public AjaxResult voteComment1Like(@RequestBody HelpVoteComment1 helpVoteComment1){

        helpVoteComment1.setLike(helpVoteComment1.getLike()+1);
        HelpVoteComment1Like r = new HelpVoteComment1Like();
        r.setDate(new Date());
        r.setUserId(SecurityUtils.getUserID());
        r.setComment1Id(helpVoteComment1.getCommentId());
        helpVoteComment1LikeMapper.insert(r);
        return AjaxResult.success(helpVoteComment1Mapper.updateByPrimaryKey(helpVoteComment1));
    }

    /**
     * 帮购一级评论取消点赞
     */
    @PostMapping("/deleteVoteComment1Like")
    public AjaxResult deleteVoteComment1Like(@RequestBody HelpVoteComment1 helpVoteComment1){

        Long userId = SecurityUtils.getUserID();

        helpVoteComment1.setLike(helpVoteComment1.getLike()-1);
        List<HelpVoteComment1Like> res = helpVoteComment1LikeMapper.selectByComment1Id(helpVoteComment1.getCommentId());
        for(int w=0;w<res.size();w++){
            if(res.get(w).getUserId() == userId){
                helpVoteComment1LikeMapper.deleteByPrimaryKey(res.get(w).getResultId());
                break;
            }
        }
        return AjaxResult.success(helpVoteComment1Mapper.updateByPrimaryKey(helpVoteComment1));
    }


    /**
     * 帮购二级评论点赞
     */
    @PostMapping("/voteComment2Like")
    public AjaxResult voteComment2Like(@RequestBody HelpVoteComment2 helpVoteComment2){

        helpVoteComment2.setLike(helpVoteComment2.getLike()+1);
        HelpVoteComment2Like r = new HelpVoteComment2Like();
        r.setDate(new Date());
        r.setUserId(SecurityUtils.getUserID());
        r.setComment2Id(helpVoteComment2.getCommentId());
        helpVoteComment2LikeMapper.insert(r);
        return AjaxResult.success(helpVoteComment2Mapper.updateByPrimaryKey(helpVoteComment2));
    }

    /**
     * 帮购二级评论取消点赞
     */
    @PostMapping("/deleteVoteComment2Like")
    public AjaxResult deleteVoteComment2Like(@RequestBody HelpVoteComment2 helpVoteComment2){

        Long userId = SecurityUtils.getUserID();

        helpVoteComment2.setLike(helpVoteComment2.getLike()-1);
        List<HelpVoteComment2Like> res = helpVoteComment2LikeMapper.selectByComment2Id(helpVoteComment2.getCommentId());
        for(int w=0;w<res.size();w++){
            if(res.get(w).getUserId() == userId){
                helpVoteComment2LikeMapper.deleteByPrimaryKey(res.get(w).getResultId());
                break;
            }
        }
        return AjaxResult.success(helpVoteComment2Mapper.updateByPrimaryKey(helpVoteComment2));
    }


    /**
     * 帮购查询历史投票列表
     */

    @GetMapping("/voteList")
    public AjaxResult voteList()
    {
        Integer i = SecurityUtils.getCommunityId();
        List<HelpVote> helpVotes = helpVoteMapper.selectHelpVotesByCommunityId(i);

        Collections.reverse(helpVotes);

        return  AjaxResult.success(helpVotes);

    }


    /**
     * 帮购查询历史投票具体信息
     */

    @GetMapping("/voteInfoById")
    public AjaxResult voteInfoById(Integer i)
    {
        HelpVote h = helpVoteMapper.selectByPrimaryKey(i);

        List<HelpVoteOption> options =new ArrayList<HelpVoteOption>();
        options = helpVoteOptionMapper.selectByVoteId(h.getVoteId());

        int q = 0;
        for(int j=0;j<options.size();j++){
            q+=options.get(j).getNum();
        }

        Long userId = SecurityUtils.getUserID();
        for(int j=0;j<options.size();j++){
            HelpVoteOption a = options.get(j);
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format((float)a.getNum()/(float)q*100)+"%";
            a.setSpeed(result);

//
//            List<HelpVoteResult> res = helpVoteResultMapper.selectByOption(a.getOptionId());
//            //查询用户是否已经投过票
//            for(int w=0;w<res.size();w++){
//                if(res.get(w).getUserId() == userId){
//                    a.setCollect(true);
//                    break;
//                }
//            }
//            Map map = new HashMap();
//            map.put("userId",userId);
//            map.put("optionId",a.getOptionId());
//            if(helpVoteResultMapper.selectByOptionAndUserId(map).size()>0){
//                a.setCollect(true);
//            };

        }

        h.setOptions(options);
        return  AjaxResult.success(h);

    }


}
